//
//  AddGroupViewController.m
//  PigMarket
//
//  Created by mac on 2019/6/17.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "GroupSetUpViewController.h"
#import "SystemSetingCell.h"
#import "AddGroupChatViewController.h"
#import "ModifyGroupInfoViewController.h"
#import "ChatSetUpFooterView.h"
#import "GroupNoticeViewController.h"
#import "ChatComplaintViewController.h"
#import "GroupManagerViewController.h"

@interface GroupSetUpViewController ()<UITableViewDataSource,UITableViewDelegate>
/**
 myTableView
 */
@property (nonatomic , strong) UITableView *myTableView;
/**
 dataArr
 */
@property (nonatomic , strong) NSMutableArray *headerImgArr;
/**
 dataArr
 */
@property (nonatomic , strong) NSArray *dataArr;
/**
 头部所有头像数据  包括➕➖图片
 */
@property (nonatomic , strong) NSMutableArray *allHeaderDataArr;
/**
 我在本群的昵称
 */
@property (nonatomic , strong) NSString *myNameInGroup;
/**
 footer
 */
@property (nonatomic , strong) ChatSetUpFooterView *footerView;
/**
 群信息
 */
@property (nonatomic , strong) TIMGroupInfo *groupInfo;
/**
 自己的信息
 */
@property (nonatomic , strong) NSString *meIdentifier;
@end

@implementation GroupSetUpViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.baseNavView.navTitleLabel.text = @"群聊信息";
    [self setUpView];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initData];

}


#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
   
}
- (void)initView {
    [self.view addSubview:self.myTableView];
}

- (void) initLayout {
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(TJ_NavBarHeight);
        make.right.left.bottom.mas_equalTo(0);
    }];
}

- (void) initAction {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addGroupMemberNot:) name:NotificationAddGroupMemberChange object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteGroupMemberNot:) name:NotificationDeleteGroupMemberChange object:nil];
    [self.footerView.clearBtn addTarget:self action:@selector(clearChatRecordClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)initData {
    //获取当前登陆的用户
    self.meIdentifier = [TIMManager sharedInstance].getLoginUser;
    //获取群主信息
    @weakify(self);
    [[TIMGroupManager sharedInstance] getGroupInfo:@[self.groupId] succ:^(NSArray<TIMGroupInfo *> *arr) {
        @strongify(self);
        if (arr.count == 1) {
            self.groupInfo = arr[0];
            //群成员信息
            [self initGroupMembersData];
            
        }
    } fail:^(int code, NSString *msg) {
        @strongify(self);
        [self toastWithContent:msg];
    }];
}
//获取群成员信息
- (void)initGroupMembersData {
    [self.allHeaderDataArr removeAllObjects];
    [self.headerImgArr removeAllObjects];
    //群成员请求
    @weakify(self);
    [[TIMGroupManager sharedInstance] getGroupMembers:self.groupId succ:^(NSArray<TIMGroupMemberInfo *> *members) {
        @strongify(self);

        NSMutableArray *memberIdArr = [[NSMutableArray alloc] init];
        TIMGroupMemberInfo *selfInfo;
        for (int i =0; i < members.count; i++) {
            TIMGroupMemberInfo *member = members[i];
            if ([member.member isEqualToString:self.meIdentifier]) {
                selfInfo = member;
            } 
            
            TGroupMemberCellData *data = [[TGroupMemberCellData alloc] init];
            data.identifier = member.member;
            data.name = member.member;
            
            [self.headerImgArr addObject:data];
            
            //群成员id数组
            [memberIdArr addObject:member.member];
        }
        
        //头部所有信息数组  包括➕和➖图片
        [self.allHeaderDataArr addObjectsFromArray:self.headerImgArr];
        
        //添加➕ ➖图片
        TGroupMemberCellData *addData = [[TGroupMemberCellData alloc] init];
        addData.avatar = [UIImage imageNamed:@"chat_group_addmember"];
        [self.allHeaderDataArr addObject:addData];
        
        TGroupMemberCellData *deleteData = [[TGroupMemberCellData alloc] init];
        deleteData.avatar = [UIImage imageNamed:@"chat_group_deletemember"];;
        [self.allHeaderDataArr addObject:deleteData];
        
        //获取群成员资料信息
        [[TIMFriendshipManager sharedInstance] getUsersProfile:memberIdArr forceUpdate:YES succ:^(NSArray<TIMUserProfile *> *profiles) {
            for (int i =0; i < profiles.count; i++) {
                TIMUserProfile *profile = profiles[i];
                TGroupMemberCellData *data = self.headerImgArr[i];
                data.avatar = [UIImage imageNamed:profile.faceURL];
            }
            //我在本群的昵称并刷新数据
            self.myNameInGroup = selfInfo.nameCard;
            
            //加载固定左侧title数据
            [self initCellData];
            [self.myTableView reloadData];
        } fail:^(int code, NSString *msg) {
            [self toastWithContent:msg];
        }];
    } fail:^(int code, NSString *msg) {
        [self toastWithContent:msg];
    }];
}
- (void)initCellData {
    NSString *myName = self.myNameInGroup ? self.myNameInGroup : @"未命名";
    if ([self isGroupOwner]) {
        self.dataArr = @[@[@{@"title":@"headerInfo",@"detail":@""}],
                         @[@{@"title":@"群聊名称",@"detail":self.groupName},
                           @{@"title":@"群聊二维码",@"detail":@""},
                           @{@"title":@"群公告",@"detail":@""},
                           @{@"title":@"群管理",@"detail":@""}],
                         @[@{@"title":@"我在本群的昵称",@"detail":myName}],
                         @[@{@"title":@"投诉",@"detail":@""}]];
        

    } else {
        self.dataArr = @[@[@{@"title":@"headerInfo",@"detail":@""}],
                         @[@{@"title":@"群聊名称",@"detail":self.groupName},
                           @{@"title":@"群聊二维码",@"detail":@""},
                           @{@"title":@"群公告",@"detail":@""}],
                         @[@{@"title":@"我在本群的昵称",@"detail":myName}],
                         @[@{@"title":@"投诉",@"detail":@""}]];
        

    }
}
#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.dataArr.count > 0) {
        return 4;
    }
    return 0;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArr[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        int count = (int)self.allHeaderDataArr.count;
        CGFloat h = 0;
        if (count % 5 == 0) {
            h = (count / 5) * 90;
        } else {
            h = (count / 5 + 1) * 90;
        }
        return h;
    } else {
        return 56;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return 123;
    } else {
        return 0.001;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 3) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 123)];
        
        self.footerView = [[ChatSetUpFooterView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 113)];
        
        NSString *btnTtile = nil;
        if ([self isGroupOwner]) {
            //群主
            btnTtile = @"解散该群";
            [self.footerView.quitBtn addTarget:self action:@selector(quitGroupClick) forControlEvents:UIControlEventTouchUpInside];

        } else {
            //非群主
            btnTtile = @"退出群聊";
            [self.footerView.quitBtn addTarget:self action:@selector(exitGroupClick) forControlEvents:UIControlEventTouchUpInside];
        }
        [self.footerView.clearBtn addTarget:self action:@selector(clearChatRecordClick) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView.quitBtn setTitle:btnTtile forState:UIControlStateNormal];
        [bgView addSubview:self.footerView];
        return bgView;
    } else {
        return [[UIView alloc] init];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SystemSetingCell *cell = [SystemSetingCell cellWithTableView:tableView];
    if (self.dataArr.count > indexPath.section) {
        if ([self.dataArr[indexPath.section] count] > indexPath.row) {
            [cell configGroupCellWithGroupSetUpDic:self.dataArr[indexPath.section][indexPath.row] headInfo:self.allHeaderDataArr];
        }
    }
    
    if (indexPath.section == 0) {
        cell.accessoryType = UITableViewCellAccessoryNone;

    } else {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 0) {
        //修改群名称
        ModifyGroupInfoViewController *vc = [[ModifyGroupInfoViewController alloc] init];
        vc.groupId = self.groupId;
        vc.modifyGroupInfoType = ModifyGroupInfoTypeGroupName;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        //群聊二维码
    } else if (indexPath.section == 1 && indexPath.row == 2) {
        //群公告
        if ([self isGroupOwner]) {//判断是否是群主
            ModifyGroupInfoViewController *vc = [[ModifyGroupInfoViewController alloc] init];
            vc.groupId = self.groupInfo.group;
            vc.groupNotice = self.groupInfo.notification;
            vc.modifyGroupInfoType = ModifyGroupInfoTypeNotice;
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            GroupNoticeViewController *vc = [[GroupNoticeViewController alloc] init];
            vc.groupInfo = self.groupInfo;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } else if (indexPath.section == 1 && indexPath.row == 3) {
        //群管理
        GroupManagerViewController *vc = [[GroupManagerViewController alloc] init];
        vc.groupId = self.groupId;
        vc.tIMGroupAddOpt = self.groupInfo.addOpt;
        vc.groupMemberArr = self.headerImgArr;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (indexPath.section == 2 && indexPath.row == 0) {
        //修改我在本群的昵称
        ModifyGroupInfoViewController *vc = [[ModifyGroupInfoViewController alloc] init];
        vc.groupId = self.groupId;
        vc.modifyGroupInfoType = ModifyGroupInfoTypeMyName;
        [self.navigationController pushViewController:vc animated:YES];

    } else if (indexPath.section == 3 && indexPath.row == 0) {
        //投诉
        ChatComplaintViewController *vc = [[ChatComplaintViewController alloc] init];
        vc.identifier = self.groupId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark - target action
- (void)addGroupMemberNot:(NSNotification *)not {
    AddGroupChatViewController *vc = [[AddGroupChatViewController alloc] init];
    vc.groupMemberHandelType = GroupMemberHandelTypeAdd;
    vc.identifier = self.groupId;
    vc.headerMemberInfoArr = self.headerImgArr;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)deleteGroupMemberNot:(NSNotification *)not {
    AddGroupChatViewController *vc = [[AddGroupChatViewController alloc] init];
    vc.identifier = self.groupId;
    vc.groupMemberHandelType = GroupMemberHandelTypeDelete;
    vc.headerMemberInfoArr = self.headerImgArr;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)clearChatRecordClick {
    @weakify(self);
    [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"是否清空聊天记录" confirmBtnTitle:@"确定" confirmBlock:^{
        @strongify(self);
        BOOL deleteStatus = [[TIMManager sharedInstance] deleteConversationAndMessages:TIM_GROUP receiver:self.groupId];
        if (deleteStatus) {
            [self toastWithContent:@"删除成功"];
        } else {
            [self toastWithContent:@"删除失败"];
        }
    } cancelBlock:nil];
}
//解散群组
- (void)quitGroupClick {
    [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"您确定要解散该群？" confirmBtnTitle:@"确定" confirmBlock:^{
        @weakify(self);
        [[TIMGroupManager sharedInstance] deleteGroup:self.groupId succ:^{
            @strongify(self);
            [self toastWithContent:@"解散成功"];
            [[TIMManager sharedInstance] deleteConversationAndMessages:TIM_GROUP receiver:self.groupId];
            for (UIViewController *vc in self.navigationController.viewControllers) {
                if ([vc isKindOfClass:[@"RecentlyChatListViewController" class]]) {
                    [self.navigationController popToViewController:vc animated:YES];
                }
            }
        } fail:^(int code, NSString *msg) {
            @strongify(self);
            [self toastWithContent:msg];
        }];
    } cancelBlock:nil];
}
//退出该群
- (void)exitGroupClick {
    [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"您确定要退出该群？" confirmBtnTitle:@"确定" confirmBlock:^{
        @weakify(self);
        [[TIMGroupManager sharedInstance] quitGroup:self.groupId succ:^{
            @strongify(self);
            [self toastWithContent:@"退出成功"];
            [[TIMManager sharedInstance] deleteConversationAndMessages:TIM_GROUP receiver:self.groupId];

           // [self.rtNavigationController removeViewControllerWithName:@"ChatViewController"];
            [self.navigationController popViewControllerAnimated:YES];
            
        } fail:^(int code, NSString *msg) {
            @strongify(self);
            [self toastWithContent:msg];
        }];
    } cancelBlock:nil];
}
#pragma mark - private method
//判断是否是群主
- (BOOL)isGroupOwner {
    if ([self.groupInfo.owner isEqualToString:[[TIMManager sharedInstance] getLoginUser]]) {
        //群主
        return YES;
    } else {
        //非群主
        return NO;
    }
    return NO;
}
#pragma mark - getter and setter
- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}
- (NSMutableArray *)headerImgArr {
    if (!_headerImgArr) {
        _headerImgArr = [[NSMutableArray alloc] init];
    }
    return _headerImgArr;
}
- (NSArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSArray alloc] init];
    }
    return _dataArr;
}
- (NSMutableArray *)allHeaderDataArr {
    if (!_allHeaderDataArr) {
        _allHeaderDataArr = [[NSMutableArray alloc] init];
    }
    return _allHeaderDataArr;
}
@end


